package com.neu.question.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neu.question.beans.PageVO;
import com.neu.question.beans.ResultVO;
import com.neu.question.common.utils.DateUtil;
import com.neu.question.common.utils.UUIDUtil;
import com.neu.question.domain.*;
import com.neu.question.form.EndUserForm;
import com.neu.question.form.SearchForm;
import com.neu.question.mapper.UserInfoMapper;
import com.neu.question.service.RespondentInfoService;
import com.neu.question.mapper.RespondentInfoMapper;
import com.neu.question.service.UserInfoService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.apache.poi.ss.usermodel.*;

import javax.xml.crypto.Data;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
* @author DELL
* @description 针对表【respondent_info(答者表)】的数据库操作Service实现
* @createDate 2022-11-04 16:15:09
*/
@Service
public class RespondentInfoServiceImpl extends ServiceImpl<RespondentInfoMapper, RespondentInfo>
    implements RespondentInfoService {

    @Autowired
    private RespondentInfoMapper respondentInfoMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private RespondentInfoService respondentInfoService;

    @Autowired
    private UserInfoService userInfoService;


    @Override
    public PageVO list(Integer page, Integer size) {
        Page<RespondentInfo> endUserInfoPage = new Page<>(page, size);
//        QueryWrapper<RespondentInfo> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("tenants_id", name);
        Page<RespondentInfo> endUserInfoPage1 = respondentInfoMapper.selectPage(endUserInfoPage, null);
        PageVO pageVO = new PageVO();
        pageVO.setTotal(endUserInfoPage1.getTotal());

        List<RespondentInfo> records = endUserInfoPage1.getRecords();
        List<EndRespond> endUsers = new ArrayList<>();
        EndRespond endUser = null;
        UserInfo userInfo = null;
        for (RespondentInfo re : records
        ) {
            endUser = new EndRespond();
            userInfo = userInfoMapper.selectById(re.getUserId());
            endUser = endUser.create(re, userInfo.getUsername(), userInfo.getPhoneNum(), userInfo.getStatus());
            endUsers.add(endUser);
        }
        pageVO.setData(endUsers);
        return pageVO;
    }

    @Override
    public PageVO search(SearchForm searchForm) {
        // 模糊查询加分页
        Page<RespondentInfo> endUserInfoPage = new Page<>(searchForm.getPage(), searchForm.getSize());
        Page<UserInfo> userInfoPage = new Page<>(searchForm.getPage(), searchForm.getSize());
        Page<RespondentInfo> endUserInfoPage1 = null;
        Page<UserInfo> userInfoPage1 = null;
        PageVO pageVO = new PageVO();

        List<EndRespond> endUsers = new ArrayList<>();
        if (searchForm.getValue().equals("")) {
//            endUserInfoPage1 = this.endUserInfoMapper.selectPage(endUserInfoPage, null);
        } else {
            // 判断查询key
            if (searchForm.getKey().equals("username")) {
                QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.like(searchForm.getKey(), searchForm.getValue());
                queryWrapper.eq("role_id", "3");
//                System.out.println( searchForm.getTename());
                userInfoPage1 = userInfoMapper.selectPage(userInfoPage, queryWrapper);
                pageVO.setTotal(userInfoPage1.getTotal());
                List<UserInfo> records1 = userInfoPage1.getRecords();
                for (UserInfo u : records1
                ) {
                    EndRespond user = new EndRespond();
                    QueryWrapper<RespondentInfo> endUserInfoQueryWrapper = new QueryWrapper<>();
                    endUserInfoQueryWrapper.eq("user_id", u.getId());
//                    System.out.println(u.getId());

//                    System.out.println(searchForm.getTename());
//                    endUserInfoQueryWrapper.eq("tenants_id", searchForm.getTename());

                    RespondentInfo one = respondentInfoService.getOne(endUserInfoQueryWrapper);
                    if (one != null) {
//                        System.out.println("******");
//                        System.out.println(one.getQuestionnaireId());
                        user = user.create(one, u.getUsername(), u.getPhoneNum(), u.getStatus());
                        endUsers.add(user);
                    }

                }

            } else {
//                System.out.println("id");
                QueryWrapper<RespondentInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.like(searchForm.getKey(), searchForm.getValue());
//                queryWrapper.eq("tenants_id", searchForm.getTename());
                endUserInfoPage1 = respondentInfoMapper.selectPage(endUserInfoPage, queryWrapper);
                pageVO.setTotal(endUserInfoPage1.getTotal());
                List<RespondentInfo> records = endUserInfoPage1.getRecords();

                EndRespond endUser = null;
                UserInfo userInfo = null;
                for (RespondentInfo re : records
                ) {
                    endUser = new EndRespond();
                    userInfo = userInfoMapper.selectById(re.getUserId());
                    endUser = endUser.create(re, userInfo.getUsername(), userInfo.getPhoneNum(), userInfo.getStatus());
                    endUsers.add(endUser);
                }

            }

        }


        pageVO.setData(endUsers);


        return pageVO;
    }

    @Override
    public int save(EndUserForm endUserForm) {
        //tenantsid 是 email
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();

        if (endUserForm.getUsername() != null) {
            queryWrapper.eq("username", endUserForm.getUsername());
            if (userInfoService.getOne(queryWrapper) != null) {
                //用户名已经存在
                return 3;
            }

        }
        if (endUserForm.getPhoneNum() != null) {
            QueryWrapper<UserInfo> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("phone_num", endUserForm.getPhoneNum());
            UserInfo one = userInfoService.getOne(queryWrapper1);
//            System.out.println(one.getPhoneNum());
            if (userInfoService.getOne(queryWrapper1) != null) {
                //电话号已经存在
                return 4;
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("username", endUserForm.getUsername());
        map.put("phoneNum", endUserForm.getPhoneNum());
        map.put("password", endUserForm.getPassword());
        map.put("roleId", "3");
        String id = UUIDUtil.getOneUUID();
        map.put("id", id);
        //创建时间
        Date date = DateUtil.getCreateTime();
        map.put("creationDate", date);
        map.put("lastUpdateDate", date);
        //创建人
        //String createduserid = map.get("id").toString();
        //Map<String,Object> querymap = new JSONObject();
        //querymap.put("id",createduserid);
        // Map<String,Object> queryresult = userEntityMapper.queryUserById(querymap);
        //String user = queryresult.get("username").toString();
        String user = endUserForm.getOpusername();

        map.put("createdBy", user);
        map.put("lastUpdatedBy", user);
        //前台传入的时间戳转换
//        String startTimeStr = endUserForm.getStartTime();
//        String endTimeStr = endUserForm.getStopTime();
//        Date startTime = DateUtil.getMyTime(startTimeStr);
//        Date endTime = DateUtil.getMyTime(endTimeStr);
//        System.out.println("222222");
//        System.out.println(endTime);
//        map.put("startTime", startTime);
//        map.put("stopTime", endTime);

        Date d = endUserForm.getStartTime();

        map.put("startTime", d);
        map.put("stopTime", endUserForm.getStopTime());
        //对时间进行增减 减去八小时


        int result = userInfoMapper.addUserInfo(map);
        UserInfo userInfo = userInfoMapper.selectById(id);
        Date date1 = new Date();
        //判断时间来决定状态
        if (endUserForm.getStartTime().after(date1) || endUserForm.getStopTime().before(date1)) {
            userInfo.setStatus("0");
            userInfoService.saveOrUpdate(userInfo);
        }

        //创建答者
        RespondentInfo respondentInfo = new RespondentInfo();
        respondentInfo.setUserId(id);
        //tenantsid 邮箱
        respondentInfo.setEmail(endUserForm.getTenantsId());
        respondentInfo.setGroupId("1");
        respondentInfo.setQuestionnaireId("");
        if (respondentInfoService.save(respondentInfo)) {
            //如果成功 不操作
            return result;
        } else {
            //成功存入User_info  但是没有成功存入 respondent_info
            return 5;
        }


    }

    @Override
    public int saveFromExcel(EndUserForm endUserForm) {
        //tenantsid 是 email
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        if (endUserForm.getUsername() != null) {
            queryWrapper.eq("username", endUserForm.getUsername());
            if (userInfoService.getOne(queryWrapper) != null) {
                //用户名已经存在
                return 3;
            }

        }
        if (endUserForm.getPhoneNum() != null) {
            QueryWrapper<UserInfo> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("phone_num", endUserForm.getPhoneNum());
            UserInfo one = userInfoService.getOne(queryWrapper1);
//            System.out.println(one.getPhoneNum());
            if (userInfoService.getOne(queryWrapper1) != null) {
                //电话号已经存在
                return 4;
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("username", endUserForm.getUsername());
        map.put("phoneNum", endUserForm.getPhoneNum());
        map.put("password", endUserForm.getPassword());
        map.put("roleId", "3");
        String id = UUIDUtil.getOneUUID();
        map.put("id", id);
        //创建时间
        Date date = DateUtil.getCreateTime();
        map.put("creationDate", date);
        map.put("lastUpdateDate", date);
        //创建人
        //String createduserid = map.get("id").toString();
        //Map<String,Object> querymap = new JSONObject();
        //querymap.put("id",createduserid);
        // Map<String,Object> queryresult = userEntityMapper.queryUserById(querymap);
        //String user = queryresult.get("username").toString();
        String user = endUserForm.getOpusername();

        map.put("createdBy", user);
        map.put("lastUpdatedBy", user);
        //前台传入的时间戳转换
//        String startTimeStr = endUserForm.getStartTime();
//        String endTimeStr = endUserForm.getStopTime();
//        Date startTime = DateUtil.getMyTime(startTimeStr);
//        Date endTime = DateUtil.getMyTime(endTimeStr);
//        System.out.println("222222");
//        System.out.println(endTime);
//        map.put("startTime", startTime);
//        map.put("stopTime", endTime);


        //给 24小时的使用时间
        Date th = new Date();
        Date th1 = new Date();
        th.setTime(th.getTime() + 8*60*60*1000);
        map.put("startTime", th);
        th1.setTime(th1.getTime() + 32*60*60*1000);
        map.put("stopTime", th1);
//        Date d = endUserForm.getStartTime();


//        map.put("stopTime", endUserForm.getStopTime());
        //对时间进行增减 减去八小时


        int result = userInfoMapper.addUserInfo(map);
//        UserInfo userInfo = userInfoMapper.selectById(id);
//        Date date1 = new Date();
//        //判断时间来决定状态
//        if (endUserForm.getStartTime().after(date1) || endUserForm.getStopTime().before(date1)) {
//            userInfo.setStatus("0");
//            userInfoService.saveOrUpdate(userInfo);
//        }

        //创建答者
        RespondentInfo respondentInfo = new RespondentInfo();
        respondentInfo.setUserId(id);
        //tenantsid 邮箱
        respondentInfo.setEmail(endUserForm.getTenantsId());
        respondentInfo.setGroupId("1");
        respondentInfo.setQuestionnaireId(endUserForm.getQuestionnaireNum());
        if (respondentInfoService.save(respondentInfo)) {
            //如果成功 不操作
            return result;
        } else {
            //成功存入User_info  但是没有成功存入 respondent_info
            return 5;
        }
    }

    @Override
    public int update(EndUserForm endUserForm, boolean change) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();

//        UserInfo one = userInfoService.getOne(queryWrapper);
        List<UserInfo> userInfoList = userInfoService.list(queryWrapper);
        QueryWrapper<RespondentInfo> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("id", endUserForm.getId());

        //被修改的用户
        RespondentInfo one = respondentInfoService.getOne(queryWrapper1);
        String oldName = userInfoService.getById(one.getUserId()).getUsername();
        String oldPhone = userInfoService.getById(one.getUserId()).getPhoneNum();
        String oldEmail = one.getEmail();
        queryWrapper.eq("username", oldName);

        //被修改的用户
        UserInfo one1 = userInfoService.getOne(queryWrapper);

        //判断用户名
        if (!oldName.equals(endUserForm.getUsername())) {
            queryWrapper.clear();
            queryWrapper.eq("username", endUserForm.getUsername());
            //如果有重名
            if (userInfoService.getOne(queryWrapper) != null) {
                //重名
                return 3;
            }
            one1.setUsername(endUserForm.getUsername());

        }
        //判断电话号
        if (!oldPhone.equals(endUserForm.getPhoneNum())) {
            queryWrapper.clear();
            queryWrapper.eq("phone_num", endUserForm.getPhoneNum());
            if (userInfoService.getOne(queryWrapper) != null) {
                //重复电话号
                return 4;
            }
            one1.setPhoneNum(endUserForm.getPhoneNum());
        }
        //判断邮箱
        if (!oldEmail.equals(endUserForm.getTenantsId())) {
            queryWrapper1.clear();
            queryWrapper1.eq("email", endUserForm.getTenantsId());
            if (respondentInfoService.getOne(queryWrapper1) != null) {
                //重复邮箱
                return 8;
            }

        }
        one1.setPassword(endUserForm.getPassword());
        one1.setStopTime(endUserForm.getStopTime());
        if (change) {
            one1.setStatus("0");
        } else {
            one1.setStatus("1");
        }
        if (!userInfoService.saveOrUpdate(one1)) {
            //user存储失败
            return 5;
        }

        one.setQuestionnaireId(endUserForm.getQuestionnaireNum());
        if (!respondentInfoService.saveOrUpdate(one)) {
            //enduser  false
            return 6;
        }


        return 1;
    }

    @Override
    public int delete(String id) {
        RespondentInfo byId = respondentInfoService.getById(id);
        UserInfo byId1 = userInfoService.getById(byId.getUserId());


        int i = respondentInfoMapper.deleteById(id);
        if (!(i == 1)) {
            //endUser 删除失败
            return 3;
        }
        int i1 = userInfoMapper.deleteById(byId1.getId());
        if (!(i1 == 1)) {
            //User 删除失败
            return 2;
        }


        return 1;
    }

    @Override
    public void create() {
        List<UserInfo> list = userInfoService.list();
        Date date = new Date();
        for (UserInfo u : list
        ) {
            if (u.getRoleId().equals("3")) {
                if (u.getStopTime().after(date) && u.getStartTime().before(date)) {
                    u.setStatus("1");
                } else {
                    u.setStatus("0");
                }
                userInfoService.saveOrUpdate(u);
            }

        }

//        return false;
    }

    @Override
    public String loadConferencePersonFile(MultipartFile file) {
        // 读取文件
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            return "文件读取失败";
        }
// 创建excel实例
        Workbook wb = null;
// 判断格式是.xlsx还是.xls
        if (file.getOriginalFilename().matches("^.+\\.(?i)(xlsx)$")) {
            try {
                wb = new XSSFWorkbook(inputStream);
            } catch (IOException e) {
                return "读取excel（xlsx）失败!";
            }

        } else {
            try {
                wb = new HSSFWorkbook(inputStream);
            } catch (IOException e) {
                return "读取excel（xls）失败!";
            }
        }
        // 获取excel第一个表格
        Sheet sheet = wb.getSheetAt(0);
        if (sheet == null || sheet.getRow(0) == null || sheet.getLastRowNum() == 0) {
            Integer n = 1;
            return "该文件没有数据!";
        }
        // 获取列数
        int column = sheet.getRow(0).getPhysicalNumberOfCells();
        // 获取行数
        int rows = sheet.getLastRowNum();
        List<String> empNoList = new ArrayList<>();
        EndUserForm e = null;
        int i1 = 0;
        int j1 = 0;
        int re = 0;
        // 遍历Excel
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (row == null) {
                continue;
            }
            e = new EndUserForm();
            e.setOpusername("excel");
            // 遍历列数，工号
            for (int j = 0; j <= column; j++){
                if (row.getCell(j) != null) {
                    row.getCell(j).setCellType(Cell.CELL_TYPE_STRING);
                    String empNo = row.getCell(j).getStringCellValue();
                    // 不为空获取工号
                    if (empNo != null) {
                        if (j == 0) {
                            e.setUsername(empNo);
                        } else if (j == 1) {
                            e.setPhoneNum(empNo);
                        } else if (j == 2) {
                            e.setPassword(empNo);
                        } else if ( j == 3 ) {
                            e.setTenantsId(empNo);

                        } else if (j == 4) {
                            e.setQuestionnaireNum(empNo);
                        }

                        empNoList.add(empNo);
                    }
                }
            }
            re = respondentInfoService.saveFromExcel(e);
            if (re != 1) {
                j1 ++;
            } else {
                i1 += re;
            }

        }
        String res = null;
        if (j1 == 0) {
             res = "成功存入：" + i1 + "条数据";
        } else {
             res = "成功存入：" + i1 + "条数据\n未成功存入：" + j1 + "条数据，原因是电话号或用户名重复";
        }

        System.out.println(i1);
        // 然后以上是读取，往下写自己需要的功能
        return res;
    }

}




